<template>
  <el-dialog
    v-if="load"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="title"
    width="1000"
    @close="handleClose"
    class="order-info dialog-class"
    :z-index="2000"
  >
    <template
      v-if="!(handleType == 'add' || handleType == 'copy' || handleType == 'subTask')"
    >
      <span class="pictureTitle">单据信息</span>
      <div class="flex order-desc">
        <div class="mr-10">任务单号：{{ form.task_no }}</div>
        <div class="mr-10">任务状态：{{ form.status_text }}</div>
        <div>创建时间：{{ form.create_time }}</div>
      </div>
    </template>
    <span class="pictureTitle">商品详情</span>
    <div class="flex items-center">
      <el-button type="primary" v-if="handleType !== 'view'" @click="addPictureListFun"
        >选择商品</el-button
      >
    </div>
    <vxe-table
      ref="tableRef"
      :data="form.images_assignment_sku"
      :row-class-name="rowClassName"
      class="mt-2"
      v-if="handleType !== 'add' || form.images_assignment_sku.length"
    >
      <vxe-column type="seq" width="60" title="序号"></vxe-column>
      <vxe-column title="产品图片" width="100">
        <template #default="{ row }">
          <VImage
            :src="row.goods_sku?.attr_img_watermark || row.goods_sku?.attr_img"
            :width="60"
            :height="60"
            :preview="false"
            @click="showImage(row.sku_id || row.goods_sku?.id)"
          ></VImage>
        </template>
      </vxe-column>
      <vxe-column title="SPU" width="100">
        <template #default="{ row }">
          <div>
            <div>{{ row.goods_sku?.spu }}</div>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="SKU/自定义SKU" width="180">
        <template #default="{ row }">
          <div>
            <span>{{ row.goods_sku?.sku }}</span>
            <span class="block">自定义: {{ row.goods_sku?.custom_sku }}</span>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="产品名称" field="sku_cn_title" width="160">
        <template #default="{ row }">
          <VText :value="row.goods_sku?.sku_cn_title" :line="3"></VText>
        </template>
      </vxe-column>
      <vxe-column title="产品分类" width="200">
        <template #default="{ row }">
          <vText :value="row.goods_sku?.goods_spu?.spu_category_text" :line="2" />
        </template>
      </vxe-column>
      <vxe-column title="商品状态" width="100">
        <template #default="{ row }">
          <div>
            <div>{{ row.goods_sku?.spu_status_text }}</div>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="规格" width="80">
        <template #default="{ row }">
          <template v-if="row.goods_sku?.sku_specification">
            <div
              v-for="(item, index) in row.goods_sku?.sku_specification.header"
              :key="index"
            >
              {{ item.name }}
            </div>
          </template>
          <template v-else>--</template>
        </template>
      </vxe-column>
      <vxe-column title="采购未税报价" width="110">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price"
            :value="row.goods_sku?.supplier_quotation"
            :currency="row.currency"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="采购未税价" width="100">
        <template #default="{ row }">
          <dataAuthority
            auth="purchase_untaxed_price"
            :value="row.goods_sku?.purchase_untaxed_price"
            :currency="row.currency"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="采购含税价" width="100">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price_tax"
            :value="row.goods_sku?.unit_price_tax"
            :currency="row.currency"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column
        title="操作"
        fixed="right"
        width="100"
        align="center"
        v-if="handleType != 'view'"
      >
        <template #default="{ rowIndex }">
          <div style="color: red; cursor: pointer" @click="delFun(rowIndex)">删除</div>
        </template>
      </vxe-column>
    </vxe-table>
    <el-form
      ref="formRef"
      :model="form"
      label-align="right"
      label-width="0"
      size="default"
      label-position="top"
    >
      <div>
        <span class="pictureTitle">人员信息</span>
      </div>
      <el-row class="person-info" :gutter="20" v-if="handleType === 'view'">
        <el-col :span="8">
          <div class="order-label">产品开发人员：</div>
          <div class="order-value">{{ form.developer_user_text }}</div>
        </el-col>
        <el-col :span="8">
          <div class="order-label">运营人员：</div>
          <div class="order-value">
            {{ form.operators_user_ids_text && form.operators_user_ids_text.join("、") }}
          </div>
        </el-col>
        <el-col :span="8">
          <div class="order-label">图片处理人员：</div>
          <div class="order-value">{{ form.designer_user_text }}</div>
        </el-col>
        <el-col :span="8">
          <div class="order-label">摄影人员：</div>
          <div class="order-value">{{ form.photography_user_text }}</div>
        </el-col>
        <el-col :span="8">
          <div class="order-label">编辑人员：</div>
          <div class="order-value">{{ form.edit_user_text }}</div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-else>
        <template v-if="handleType == 'subTask'">
          <el-col :span="6">
            <el-form-item label="设计审核人" required>
              <select-personnel
                v-model="form.designer_reviewer"
                placeholder="设计审核人"
              ></select-personnel>
            </el-form-item>
          </el-col>
        </template>
        <template v-else>
          <el-col :span="6">
            <el-form-item label="产品开发人员" required>
              <select-personnel
                v-model="form.developer_user"
                placeholder="开发人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="relative" label="运营审核" required>
              <template #label>
                运营审核
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="1、维护多个运营人员，运营审核时需全部审核通过<br/>2、加载：用于获取所选SKU中，推荐平台/站点所维护的运营人员，默认去重"
                  raw-content
                  placement="top"
                >
                  <svg-icon
                    class="absolute left-[70px] top-1"
                    icon-class="QuestionFilled"
                  ></svg-icon>
                </el-tooltip>
                <el-button class="ml-[14px]" type="primary" link @click="handleLoader"
                  >加载</el-button
                >
              </template>
              <select-personnel
                v-model="form.operators_user_ids"
                :multiple="true"
                placeholder="运营人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="6">
          <el-form-item label="图片处理人员">
            <select-personnel
              v-model="form.designer_user"
              placeholder="图片处理人员"
            ></select-personnel>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="摄影人员">
            <select-personnel
              v-model="form.photography_user"
              placeholder="摄影人员"
            ></select-personnel>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="编辑人员">
            <select-personnel
              v-model="form.edit_user"
              placeholder="编辑人员"
            ></select-personnel>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="渲染人员">
            <select-personnel
              v-model="form.render_user"
              placeholder="渲染人员"
            ></select-personnel>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="协助人员">
            <select-personnel
              v-model="form.assistance_user"
              placeholder="协助人员"
            ></select-personnel>
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <span class="pictureTitle">任务要求</span>
      </div>
      <div class="pb-2 text-[#999]">
        注：任务等级，环境电子基于销量进行选择A (1000以上) B (600-999) C (300-599) D
        (300以下)
      </div>
      <el-row :gutter="20" v-if="handleType !== 'view'">
        <el-col :span="16">
          <el-form-item label="任务等级/类型">
            <VGroup>
              <el-select
                v-model="form.task_priority"
                class="w-40"
                placeholder="请选择任务等级"
                clearable
                style="width: 140px"
              >
                <el-option
                  v-for="item in options['assignment.ImagesAssignment']?.[0]
                    .taskPriorityText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <SelectTaskTypeByUid
                v-model="form.task_type"
                placeholder="请选择任务类型"
                multiple
                clearable
              ></SelectTaskTypeByUid>
            </VGroup>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务优先级">
            <el-select
              class="w-full"
              v-model="form.priority"
              placeholder="请选择任务优先级"
              clearable
            >
              <el-option
                v-for="item in options['assignment.ImagesAssignment']?.[0].priorityText02"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品类型">
            <el-select
              class="w-full"
              v-model="form.product_type"
              placeholder="产品类型"
              clearable
            >
              <el-option
                v-for="item in options['assignment.ImagesAssignment']?.[0]
                  .productTypeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设计品牌">
            <select-brand
              class="w-full"
              v-model="form.brand_id"
              :multiple="true"
              placeholder="设计品牌"
            ></select-brand>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="图片数量">
            <el-select
              class="w-full"
              v-model="form.image_total"
              placeholder="产品类型"
              clearable
            >
              <el-option
                v-for="item in options['assignment.ImagesAssignment']?.[0].imageTotalText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="relative" :span="8">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="精铺：至少30天工期；精品：至少40天工期<br/>按各部门排期，可自行调整"
            raw-content
            placement="top"
          >
            <svg-icon class="absolute left-24 top-1" icon-class="hint_cover2"></svg-icon>
          </el-tooltip>

          <el-form-item label="预期完成时间">
            <el-date-picker
              style="width: 100%"
              :disabled-date="UtilEleDisabledDay"
              :disabled-hours="UtilEleDisabledHour"
              :disabled-minutes="UtilEleDisabledMinute"
              :disabled-seconds="UtilEleDisabledSecond"
              v-model="form.expected_time"
              type="datetime"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请输入"
            />
            <div>
              <el-button
                size="small"
                v-for="(item, index) in timeList"
                :key="index"
                @click="checkTime(item.value)"
                >{{ item.label }}</el-button
              >
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="目标套数（环境电子）">
            <el-input
              v-model="form.converted_quantity"
              placeholder="请输入目标套数"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务备注">
            <el-input
              v-model="form.task_remark"
              :rows="2"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="处理人备注">
            <el-input
              v-model="form.handle_remark"
              :rows="2"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <DetailTask v-else :detail="form" />
    </el-form>

    <div v-if="handleType !== 'view'">
      <div style="font-weight: 700" class="text-base">任务要求附件</div>
      <template v-if="form.task_file?.length || handleType != 'view'">
        <FileUpload
          v-model="form.task_file"
          :isShowTip="false"
          :progress="true"
        ></FileUpload>
      </template>
      <div class="text-[#999999]" v-else>暂无附件</div>
    </div>
    <template v-if="handleType == 'edit' || handleType == 'view'">
      <div class="mb-2">
        <div class="pictureTitle my-2">任务标签</div>
        <taskTag
          v-if="handleType == 'subTask'"
          v-model="form.images_task_tag"
          @changeRole="changeRole"
        ></taskTag>
      </div>

      <el-tabs v-model="activeName" type="card">
        <el-tab-pane
          :label="item.goods_sku?.sku"
          :name="item.goods_sku?.custom_sku"
          v-for="(item, index) in form.images_assignment_sku"
          :key="index"
        >
          <template #label>
            {{ item.goods_sku?.sku || item.goods_sku?.custom_sku }}
          </template>
          <div>
            <span class="pictureTitle">文案编辑</span>
            <template v-if="item.copy_writing_file?.length || handleType != 'view'">
              <FileUpload
                v-model="item.copy_writing_file"
                :isShowTip="false"
                :progress="true"
                disabled
              ></FileUpload>
            </template>
            <div class="text-[#999999]" v-else>暂未上传</div>
          </div>
          <div>
            <span class="pictureTitle">任务图片</span>
            <Picture
              ref="PictureRef"
              v-model="item.images_assignment_list"
              :currentIndex="index"
            ></Picture>
          </div>
          <routineModule
            v-model="item.images_assignment_screenshot_list"
            tips="注：此图片仅用于判断任务的完成情况，无法推送到产品资料，支持绑定图片绩效标签；"
          ></routineModule>
          <div
            class="border border-[var(--base-border-color)] flex justify-between mt-2"
            style="padding: 10px 8px; border-radius: 8px 8px 0px 0px"
          >
            <div>文件</div>
            <div v-if="handleType != 'view'">
              <el-button type="primary" @click="updataFile(item, index)"
                >上传文件</el-button
              >
            </div>
          </div>

          <vxe-table
            border
            show-overflow
            :data="item.images_assignment_file"
            :column-config="{ resizable: true }"
            :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
            :row-class-name="rowClassName"
          >
            <vxe-column type="seq" title="序号" width="60"></vxe-column>
            <vxe-column field="name" title="文件名称">
              <template #edit="{ row }">
                {{ row.name }}
              </template>
            </vxe-column>
            <vxe-column field="certificate_type" title="文件类型">
              <template #default="{ row }">
                <el-select
                  v-model="row.type"
                  collapse-tags
                  placeholder="请选择"
                  clearable
                  style="width: 148px"
                >
                  <el-option
                    v-for="item in options['assignment.ImagesAssignment']?.[0].typeText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="operation" title="操作">
              <template #default="{ row }">
                <el-button type="primary" @click="onDownload(row)">下载</el-button>
                <el-button
                  type="danger"
                  @click="inspectionItemsReduce(item.images_assignment_file, index)"
                  >删除</el-button
                >
              </template>
            </vxe-column>
          </vxe-table>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <template v-if="handleType == 'view'">
        <el-button @click="handleClose">关闭</el-button>
      </template>
      <template v-else>
        <div class="flex justify-center items-center">
          <el-radio-group v-if="handleType == 'add'" class="mr-8" v-model="createType">
            <el-radio :label="1" :value="1" size="large">默认不拆分</el-radio>
            <el-radio :label="2" :value="2" size="large">按SPU拆分</el-radio>
            <el-radio :label="3" :value="3" size="large">按SKU拆分</el-radio>
          </el-radio-group>
          <div>
            <el-button class="ml-auto" @click="handleClose">取消</el-button>
            <el-button type="primary" :loading="loading" @click="addTaskFun">
              保存
            </el-button>
          </div>
          <div class="ml-8 text-left notice">
            <template v-if="handleType != 'subTask'">
              <div>
                <el-checkbox
                  v-model="form.is_notify_custom"
                  :true-label="1"
                  :false-label="0"
                  label="自定义通知人员"
                  size="large"
                >
                  <select-personnel
                    class="w-60"
                    v-model="form.custom_user"
                    :multiple="true"
                    placeholder="自定义通知人员"
                  ></select-personnel>
                </el-checkbox>
              </div>

              <!-- <div class="ml-2"> -->
              <div>
                <el-checkbox
                  v-model="form.is_notify_operator"
                  :true-label="1"
                  :false-label="0"
                  label="消息通知运营人员"
                  size="large"
                />
              </div>
              <div>
                <el-checkbox
                  v-model="form.is_notify_developer"
                  :true-label="1"
                  :false-label="0"
                  label="消息通知开发人员"
                  size="large"
                />
              </div>
              <!-- </div> -->
            </template>
          </div>
        </div>
      </template>
    </template>
  </el-dialog>
  <addPictureList
    ref="addPictureListRef"
    :getTable="getProductID"
    @addPictureListQuery="addPictureListQuery"
  />
  <dialogUpload ref="dialogUploadRef" @uploadFile="uploadFile"></dialogUpload>
  <checkImage ref="checkImageRef"></checkImage>
</template>

<script setup>
import { nextTick, onMounted, ref, toRefs, reactive } from "vue";
import addPictureList from "./addPictureList.vue";
import Picture from "./Picture/index";
import { ElMessageBox, ElMessage } from "element-plus";
import dialogUpload from "./dialogUpload.vue";
import FileUpload from "@/components/FileUpload";
import DetailTask from "../components/detail/task";
import { downloadFile } from "@/utils/downloadFile.js";
import {
  createImagesAssignment,
  editImagesAssignment,
  getImagesAssignmentDetail,
  querySkuList,
} from "../api";
import SelectBrand from "@/components/SelectBrand";
import {
  UtilEleDisabledDay,
  UtilEleDisabledHour,
  UtilEleDisabledMinute,
  UtilEleDisabledSecond,
  UtilMatchPersonName,
} from "../../../../utils";
import { formatDate, deepClone } from "@/utils/index.js";
import { timeList, imageTypeText } from "../data.js";
import useCommonStore from "@/store/modules/common";
import taskTag from "./taskTag.vue";
import { getOptions } from "@/api/index";
import SelectTaskTypeByUid from "@/components/Selects/SelectTaskTypeByUid/index.vue";
import routineModule from "../components/Picture/components/routineModule.vue";
import VImage from "@/components/Image/index.vue";
import checkImage from "@/views/task/sample-list/components/checkImage.vue";

const commonStore = useCommonStore();
const personnelOptions = computed(() => {
  if (!commonStore.personnelOptions) {
    commonStore.getOrganization();
  }
  return commonStore.personnelOptions;
});

let options = reactive(inject("options"));

const statusMap = new Map([
  ["add", "新增"],
  ["edit", "编辑"],
  ["view", "查看"],
  ["copy", "新增"],
  ["subTask", "子任务创建"],
]);

const addPictureListRef = ref(null);
const dialogVisible = ref(false);

// 初始化图片
const initGallery = (flag = false) => {
  let obj = {
    custom_tag: "默认",
    image_list: [],
  };
  options.value["assignment.ImagesAssignment"]?.[0].imageTypeText &&
    options.value["assignment.ImagesAssignment"]?.[0].imageTypeText.forEach(
      (element, e) => {
        obj.image_list.push({
          label_type: element.label,
          type: element.value,
          values: [],
        });
      }
    );
  if (flag) {
    return [obj];
  } else {
    goods_spu_gallery.value = [obj];
  }
};

onMounted(() => {
  if (!commonStore.personnelOptions) {
    commonStore.getOrganization();
  }
});

const data = reactive({
  form: {
    developer_user: "", //产品开发人员
    operators_user_ids: "", // 运营人员
    photo_processor: "", // 图片处理人员
    camera_processor: "", // 摄影人员
    edit_user: "", //编辑人员
    task_priority: "", // 任务等级/类型
    task_type: [], // 任务类型
    product_type: "", // 产品类型
    brand_id: "", // 涉及品牌
    expected_time: "", // 预期完成时间
    image_total: "", // 图片数量
    task_remark: "", // 任务备注
    task_file: [], // 任务文件
    text_file: [], // 文案文件
    spu: "",
    attr_type: "",
    images_assignment_sku: [],
    is_notify_custom: 0,
    is_notify_developer: 1,
    is_notify_operator: 1,
    images_task_tag: [],
  },
  handleType: null,
  PictureRef: null,
  title: null,
  activeName: null,
  currentIndex: null,
  goods_spu_gallery: [],
  createType: 1,
  load: false,
  loading: false,
});

const {
  form,
  handleType,
  PictureRef,
  title,
  activeName,
  currentIndex,
  goods_spu_gallery,
  createType,
  load,
  loading,
} = toRefs(data);

provide("handleType", handleType);

const open = async (type, sample_spu) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  initGallery();
  if (type == "add" && sample_spu?.spu) {
    nextTick(() => {
      form.value.developer_user = sample_spu.create_user_id;
      addSamplePicture(sample_spu?.spu || sample_spu);
    });
  } else if (sample_spu) {
    getDetail(sample_spu);
  }
  dialogVisible.value = true;
};

// 获取详情
const getDetail = (id) => {
  getImagesAssignmentDetail({ task_id: id }).then((res) => {
    const data = res.data;
    data.images_assignment_sku.forEach((item, index) => {
      item.images_assignment_list =
        item.images_assignment_list && item.images_assignment_list.length
          ? item.images_assignment_list.map((j) => {
              if (j.image_list.length == 0) {
                j.image_list = initGalleryContents();
              } else {
                j.image_list = matchAndAdd(
                  goods_spu_gallery.value[0].image_list,
                  j.image_list
                );
                j.image_list = j.image_list.sort(
                  (a, b) => gallerySort(a.type) - gallerySort(b.type)
                );
              }
              return j;
            })
          : initGallery(true);
    });
    if (handleType.value == "copy" || handleType.value == "subTask") {
      data.images_assignment_sku.forEach((item, index) => {
        item.spu = data.spu;
        item.images_assignment_list = initGallery(true);
        delete item.images_assignment_screenshot_list;
      });
      delete data.status;
      delete data.status_text;
      delete data.create_time;
      delete data.expected_time;
      delete data.process_time;
      delete data.task_no;
      delete data.design_score;
      delete data.operate_score;
      delete data.images_task_tag;
    }

    form.value = data;
    if (handleType.value == "subTask") {
      form.value.pid = id;
      form.value.images_task_tag = [];
      form.value.images_task_tag.splice(-1, 0, {
        type: "add",
      });
      form.value.images_assignment_sku.forEach((item, index) => {
        item.images_assignment_list = item.images_assignment_list.map((j) => {
          j.image_list = deepClone(initGalleryContents());
          return j;
        });
      });
    }
    activeName.value = form.value.images_assignment_sku[0].custom_sku;
  });
};

// 保存图片任务
const addTaskFun = async () => {
  const formData = Object.assign({}, form.value);
  if (!formData.images_assignment_sku.length) {
    return ElMessage({
      message: "请先选择商品",
      type: "warning",
    });
  }
  formData.notify = [];
  if (formData.is_notify_operator && formData.operators_user_ids) {
    formData.notify.push(formData.operators_user_ids);
  }
  if (formData.is_notify_developer && formData.developer_user) {
    formData.notify.push(formData.developer_user);
  }
  if (formData.is_notify_custom && formData.custom_user) {
    formData.notify.push(...formData.custom_user);
  }

  if (form.value.operators_user_ids.length >= 2) {
    await handleConfirmMessage(
      "运营人员维护了多个，审核时需要全部审核通过，确认是否维护？"
    );
  }

  loading.value = true;

  if (handleType.value == "edit") {
    let spu_ids = [];
    formData.images_assignment_sku.forEach((i) => {
      if (!i.delete) {
        spu_ids.push(i.spu_id);
      }
    });
    editImagesAssignment({
      ...formData,
      spu_ids: Array.from(new Set(spu_ids)),
    })
      .then(() => {
        ElMessage({
          message: "修改成功",
          type: "success",
        });
        dialogVisible.value = false;
        emit("query");
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (handleType.value == "subTask") {
    let spu_ids = [];
    formData.images_assignment_sku.forEach((i) => {
      if (!i.delete) {
        spu_ids.push(i.spu_id);
      }
    });
    formData.images_task_tag = formData.images_task_tag.filter((i) => {
      if (!i.type) {
        return i;
      }
    });
    formData.spu_ids = spu_ids;
    createImagesAssignment({ spu_images_task: [formData] })
      .then(() => {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        dialogVisible.value = false;
        emit("query");
      })
      .finally(() => {
        loading.value = false;
      });
  } else {
    let spu_images_task;
    if (createType.value == 1) {
      let spu_ids = [];
      formData.images_assignment_sku.forEach((i) => {
        if (!i.delete) {
          spu_ids.push(i.spu_id);
        }
      });
      spu_images_task = [
        {
          ...formData,
          spu_ids: Array.from(new Set(spu_ids)),
        },
      ];
    } else if (createType.value == 2) {
      const spuImageMap = formData.images_assignment_sku.reduce((acc, image) => {
        acc[image.spu] = [...(acc[image.spu] || []), image];
        return acc;
      }, {});

      // 然后创建 spu_images_task 数组
      spu_images_task = Object.keys(spuImageMap).map((spu) => ({
        ...formData,
        images_assignment_sku: spuImageMap[spu],
        spu,
        category_id: formData.category_id || spuImageMap[spu][0].category_id,
        spu_ids: spuImageMap[spu].map((i) => i.spu_id),
      }));
    } else if (createType.value == 3) {
      spu_images_task = formData.images_assignment_sku.map((i) => {
        i.images_assignment_sku = [
          {
            spu: i.spu,
            sku: i.sku,
            category_id: i.spu_category,
            custom_sku: i.custom_sku,
            purchase_quantity: 0,
            sku_id: i.sku_id,
            sai_he_sku: i.sai_he_sku,
            spu_id: i.spu_id,
            goods_sku: i.goods_sku,
          },
        ];
        i.spu_ids = [i.spu_id];
        return {
          ...formData,
          ...i,
        };
      });
    }

    createImagesAssignment({ spu_images_task })
      .then(() => {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        dialogVisible.value = false;
        emit("query");
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

// 删除SKU
const delFun = (index) => {
  const list = form.value.images_assignment_sku.filter((i) => !i.delete);
  if (list.length <= 1) {
    ElMessage.error("至少保留一个SKU");
    return;
  }
  ElMessageBox.confirm("确定删除么", "提示")
    .then(() => {
      if (handleType.value == "add") {
        form.value.images_assignment_sku.splice(index, 1);
      } else {
        form.value.images_assignment_sku[index].delete = 1;
      }
      activeName.value = form.value.images_assignment_sku[0].goods_sku?.custom_sku;
    })
    .catch(() => {});
};

const gallerySort = (type) => {
  if (type == 3) {
    return 0;
  } else {
    return type;
  }
};

const matchAndAdd = (array1, array2) => {
  for (var i = 0; i < array1.length; i++) {
    var isDuplicate = false;
    for (var j = 0; j < array2.length; j++) {
      if (array1[i].type === array2[j].type) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      array2.push(array1[i]);
    }
  }
  return array2;
};

// 图片详情
const initGalleryContents = () => {
  let contents = [];
  imageTypeText.forEach((element, e) => {
    contents.push({
      label: element.label,
      label_type: element.label,
      type: element.value,
      showType: 0,
      values: [],
    });
  });
  return contents;
};

// 选择商品
const addPictureListFun = () => {
  nextTick(() => {
    addPictureListRef.value.clearSelectEvent();
    addPictureListRef.value.open();
  });
};

// 选择商品后回调
const addPictureListQuery = (list) => {
  const operators_user_ids = [];
  const newItem = list.map((e, idx) => {
    return {
      serial_num: idx,
      spu: e.spu,
      sku: e.sku,
      category_id: e.spu_category,
      custom_sku: e.custom_sku,
      purchase_quantity: 0,
      images_assignment_list: initGallery(true),
      file: [],
      images_assignment_file: [],
      sku_id: e.id,
      sai_he_sku: e.sai_he_sku,
      spu_id: e.spu_id,
      goods_sku: {
        attr_img: e.attr_img,
        spu: e.spu,
        sku: e.sku,
        custom_sku: e.custom_sku,
        sku_cn_title: e.sku_cn_title,
        purchase_amount: 0,
        purchase_price: e.purchase_price,
        spu_status_text: e.spu_status_text,
        supplier_quotation: e.supplier_quotation,
        purchase_untaxed_price: e.purchase_untaxed_price,
        unit_price_tax: e.unit_price_tax,
        goods_spu: {
          spu_category: e.spu_category,
          spu_category_text: e.spu_category_text,
        },
      },
      images_assignment_screenshot_list: [],
    };
  });
  form.value.images_assignment_sku.push(...newItem);

  form.value.developer_user = Number(list[0]?.developer_id);
  activeName.value = form.value.images_assignment_sku[0].custom_sku;
};

// 生成图片任务
const addSamplePicture = (spu) => {
  querySkuList({
    spu,
  }).then((res) => {
    form.value.spu = spu;
    form.value.attr_type = res.data.length > 1 ? 2 : 1;
    form.value.images_assignment_sku = res.data.map((e, idx) => {
      return {
        serial_num: idx,
        spu: e.spu,
        sku: e.sku,
        spu_category: e.spu_category,
        custom_sku: e.custom_sku,
        sku_cn_title: e.sku_cn_title,
        spu_status_text: e.spu_status_text,
        purchase_amount: 0,
        purchase_price: e.purchase_price,
        purchase_quantity: 0,
        attr_img: e.attr_img,
        // images_assignment_screenshot_list: []
      };
    });
  });
};

// 文件下载
const onDownload = (item) => {
  downloadFile(item.url, item.name);
};

// 删除附件
const inspectionItemsReduce = (item, index) => {
  if (handleType.value == "add") {
    item.splice(index, 1);
  } else {
    item[index].delete = 1;
  }
};

const handleClose = () => {
  initForm();
  emit("close");
  dialogVisible.value = false;
};

// 初始化form
const initForm = () => {
  form.value = {
    developer_user: "", //产品开发人员
    operators_user_ids: "", // 运营人员
    photo_processor: "", // 图片处理人员
    camera_processor: "", // 摄影人员
    edit_user: "", //编辑人员
    task_priority: "", // 任务等级/类型
    task_type: [], // 任务类型
    product_type: "", // 产品类型
    brand_id: [], // 涉及品牌
    expected_time: "", // 预期完成时间
    image_total: "", // 图片数量
    task_remark: "", // 任务备注
    task_file: [], // 任务文件
    text_file: [], // 文案文件
    spu: "",
    attr_type: "",
    images_assignment_sku: [],
    is_notify_operator: 1,
    is_notify_custom: 0,
    is_notify_developer: 1,
    images_task_tag: [],
  };
  createType.value = 1;
};

// 上传文件
const dialogUploadRef = ref();
const updataFile = (item, index) => {
  currentIndex.value = index;
  dialogUploadRef.value.open(item.ku);
};

// 上传文件回调
const uploadFile = (list) => {
  const newItem = list.map((item) => {
    return {
      type: item.type,
      name: item.filename,
      url: item.filepath,
    };
  });

  form.value.images_assignment_sku[currentIndex.value].images_assignment_file.push(
    ...newItem
  );
};

const rowClassName = ({ row }) => {
  if (row.delete === 1) {
    return "hidden-row";
  }
  return "";
};

const emit = defineEmits(["close", "query"]);

defineExpose({ open });

// 预期完成时间快捷方式
const checkTime = (value) => {
  const date = new Date();
  date.setTime(date.getTime() + 3600 * 1000 * 24 * value);
  form.value.expected_time = formatDate(date);
};

const changeRole = (item) => {
  if (!form.value[item.ruleType]) {
    ElMessage.error("请维护对应角色的人员");
  }
  form.value.images_task_tag[item.index].user_id = form.value[item.ruleType];
  form.value.images_task_tag[item.index].username = findUserNamesById(
    form.value[item.ruleType]
  );
};

const findUserNamesById = (userIds) => {
  if (!userIds) return "";

  const options = personnelOptions.value; // 从外部获取用户数据
  const selectedUserNames = new Set();

  const dfs = (node) => {
    if (!node) return;
    if (node.user_id === userIds) {
      selectedUserNames.add(node.name);
    }

    if (node.sub && node.sub.length > 0) {
      for (const subNode of node.sub) {
        dfs(subNode);
      }
    }
  };

  for (const option of options) {
    dfs(option);
  }

  return Array.from(selectedUserNames)[0]; // 返回找到的用户名数组
};

const checkImageRef = ref();
const showImage = (sku_id) => {
  checkImageRef.value.open(sku_id);
};

// 获取当前选中商品id
const getProductID = () => {
  let sku_ids = form.value.images_assignment_sku.map((i) => i.sku_id);
  return sku_ids;
};

// 加载运营人员
const handleLoader = async () => {
  const sku_ids = form.value.images_assignment_sku
    .filter((i) => !i.delete)
    .map((i) => i.sku_id);
  if (sku_ids.length == 0) {
    return ElMessage.error("请先选择商品");
  }

  try {
    const res = await querySkuList({
      sku_id: sku_ids,
    });
    const operators_user_ids = [];
    res.data.forEach((e) => {
      e.goods_sku_recommended_platform.map((i) => {
        if (i.operation_user_ids?.length) {
          operators_user_ids.push(...i.operation_user_ids);
        }
      });
    });
    form.value.operators_user_ids = Array.from(new Set(operators_user_ids));
  } catch (error) {
    console.error(error);
  }
};

// 确认弹窗
const handleConfirmMessage = async (message) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(message, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        resolve();
      })
      .catch(() => {
        reject();
      });
  });
};
</script>
<style lang="scss" scoped>
:deep(.el-scrollbar__view) {
  overflow-y: hidden;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

.listMr {
  margin-right: 18px;

  &:nth-of-type(6n + 6) {
    margin-right: 0;
  }
}

.listMrVideo {
  margin-right: 19px;

  &:nth-of-type(4n + 4) {
    margin-right: 0;
  }
}

.pictureTitle {
  font-weight: bold;
  position: relative;
  padding-left: 6px;
  font-size: 16px;
  color: var(--base-sub-text-color);

  &::after {
    content: "";
    height: 14px;
    width: 2px;
    position: absolute;
    left: 0;
    top: 0;
    align-items: center;
    background-color: #3366f1;
  }
}

.item_width {
  width: 566px;
}

.order-info {
  .pictureTitle {
    padding: 16px 0 16px 4px;
    position: relative;
    font-size: 16px;
    color: var(--base-sub-text-color);
    font-weight: 500;
    display: inline-block;
  }

  .pictureTitle::after {
    content: "";
    height: 14px;
    width: 2px;
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -8px;
    align-items: center;
    background-color: #3366f1;
  }

  .order-desc {
    padding-bottom: 8px;
    font-size: 14px;
    color: #3a4259;
  }

  .spu-txt {
    color: #3a4259;
    font-size: 14px;
  }

  .order-label,
  .order-value {
    display: inline-block;
  }

  .order-label {
    color: #999;
    width: 100px;
    text-align: right;
  }

  .order-value {
    color: #333;
  }

  .person-info {
    .el-col:nth-last-of-type(-n + 2) {
      padding-top: 16px;
    }
  }
}

:deep(.upload-file-uploader) {
  .el-upload.el-upload--text {
    button.el-button {
      padding: 8px 0;
    }
  }
}

.notice {
  line-height: normal;
  :deep(.el-checkbox.el-checkbox--large) {
    height: 28px;
  }
}

:deep(.el-tabs > .el-tabs__header .el-tabs__nav) {
  border-color: var(--base-border-color);
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
  border-color: var(--base-border-color);
}
</style>
<style lang="scss" scoped>
.hidden-row {
  display: none;
}

:deep(.el-tabs > .el-tabs__header .el-tabs__nav) {
  border-color: var(--base-border-color);
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
  border-color: var(--base-border-color);
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  border-left: 1px solid var(--base-border-color);
  border-color: var(--base-border-color);
}

:deep(.el-tabs--card > .el-tabs__header) {
  border-color: var(--base-border-color);
}
</style>
